<template>
  <div class='container'>
    <div class="app-container">
   <el-card class="box-card">
  <div slot="header" class="clearfix">
    <span>{{type ? '试题修改': '试题录入'}}</span>
  </div>
 <el-row :gutter="15">
      <el-form ref="formRef" :model="form" :rules="rules" size="medium" label-width="100px">
      <!-- 学科 -->
        <el-col :span="24">
          <el-form-item label="学科：" prop="subjectID" label-width="120px">
            <el-select v-model="form.subjectID" placeholder="请选择"  style="width: 400px"  @change="chooseSub" >
              <el-option v-for="(item, index) in subjectNameOptions" :key="index" :label="item.label"
                :value="item.value" ></el-option>
           </el-select>
          </el-form-item>
        </el-col>
      <!-- 目录 -->
        <el-col :span="24">
          <el-form-item label="目录：" prop="catalogID" label-width="120px">
            <el-select v-model="form.catalogID" placeholder="请选择"  style="width: 400px" >
              <el-option v-for="(item, index) in directoryNameOptions" :key="index" :label="item.label"
                :value="item.value" ></el-option>
            </el-select>
          </el-form-item>
        </el-col>
      <!-- 企业 -->
        <el-col :span="24">
          <el-form-item label="企业：" prop="enterpriseID" label-width="120px">
            <el-select v-model="form.enterpriseID" placeholder="请选择"  style="width: 400px" >
              <el-option v-for="(item, index) in shortNameOptions" :key="index" :label="item.shortName"
                :value="item.id" ></el-option>
            </el-select>
          </el-form-item>
        </el-col>
      <!-- 城市 -->
        <el-col :span="12">
          <el-form-item label="城市：" prop="province" label-width="120px">
               <div class="cityRay">
                 <el-select v-model="form.province" placeholder="请选择"  style="width: 197px"  @change="chooseCity" class="city">
              <el-option v-for="(item, index) in provinceOptions" :key="index"
                :value="item" ></el-option>
            </el-select>
                <el-select v-model="form.city" placeholder="请选择"  style="width: 197px;margin-left: 6px"  class="city">
              <el-option v-for="(item, index) in cityOptions" :key="index"
                :value="item" ></el-option>
            </el-select>
               </div>
          </el-form-item>
        </el-col>
      <!-- 方向 -->
        <el-col :span="24">
          <el-form-item label="方向：" prop="direction" label-width="120px">
            <el-select v-model="form.direction" placeholder="请选择"  style="width: 400px" >
              <el-option v-for="(item, index) in directionOptions" :key="index"
                :value="item" :disabled="item.disabled"></el-option>
            </el-select>
          </el-form-item>
        </el-col>
      <!-- 题型 -->
         <el-col :span="24">
          <el-form-item label="题型：" prop="questionType" label-width="120px">
            <el-radio-group v-model="form.questionType" size="medium">
              <el-radio v-for="(item, index) in questionTypeOptions" :key="index" :label="item.value.toString()"
               @change="changeItem(item.value.toString())">{{item.label}}</el-radio>
            </el-radio-group>
          </el-form-item>
        </el-col>
      <!-- 难度 -->
        <el-col :span="24">
          <el-form-item label="难度：" prop="difficulty" label-width="120px">
            <el-radio-group v-model="form.difficulty" size="medium">
              <el-radio v-for="(item, index) in difficultyOptions" :key="index" :label="item.value.toString()"
                >{{item.label}}</el-radio>
            </el-radio-group>
          </el-form-item>
        </el-col>
      <!-- 题干 -->
        <el-col :span="24">
          <el-form-item label="题干：" prop="question" label-width="120px">
            <quill-editor ref="questionRef" @getText="getQuestion"></quill-editor>
          </el-form-item>
        </el-col>
      <!-- 选项 -->
        <el-col :span="24" v-if="showOption">
          <el-form-item label="选项：" prop="options" label-width="120px">
              <div v-for="(item, index) in form.options" :key="index" class="option_item">
                <el-radio :label="index" v-model="radio" v-if="changeOption" @change="optionChange(radio)">
                  {{item.code+'：'}}
                </el-radio>
                <el-checkbox v-model="item.isRight" v-else>{{item.code+'：'}}</el-checkbox>
                <el-input v-model="item.title" type="text" style="width:240px"></el-input>
                <el-upload
                  class="avatar-uploader"
                  action="#"
                  :show-file-list="false"
                  :http-request="(options) =>onUpload(options, index)">
                  <span>上传图片</span>
                  <i class="el-icon-circle-close icon" @click="delOption(index,$event)"></i>
                </el-upload>
            </div>
            <el-row>
                <el-button type="danger" size="small" :disabled="form.questionType === 1" @click="AddOption">+增加选项与答案</el-button>
              </el-row>
          </el-form-item>
        </el-col>
      <!-- 解析视频 -->
        <el-col :span="24">
          <el-form-item label="解析视频：" prop="videoURL" label-width="120px">
            <el-input v-model="form.videoURL"  :style="{width: '40%'}"></el-input>
          </el-form-item>
        </el-col>
      <!-- 答案解析 -->
        <el-col :span="24">
          <el-form-item label="答案解析：" prop="answer" label-width="120px">
            <quill-editor ref="answerRef" @getText="getAnswer"></quill-editor>
          </el-form-item>
        </el-col>
      <!-- 题目备注 -->
        <el-col :span="24">
          <el-form-item label="题目备注：" prop="remarks" label-width="120px">
            <el-input v-model="form.remarks" type="textarea" :autosize="{minRows: 4, maxRows: 4}"
              :style="{width: '40%'}"></el-input>
          </el-form-item>
        </el-col>
      <!-- 试题标签 -->
        <el-col :span="24">
          <el-form-item label="试题标签：" prop="tags"  label-width="120px">
            <el-select
              v-model="form.tags"
              multiple
              filterable
              default-first-option
              placeholder="请选择试题标签">
                <el-option
                  v-for="(item,index) in tagsOptions"
                  :key="index"
                  :label="item.tagName"
                  :value="item.tagName">
                </el-option>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="24">
          <el-form-item >
            <el-button :type="type ? 'success': 'primary'" size="medium" @click="onSubmit">{{type ? '确认修改': '确认提交'}}</el-button>
          </el-form-item>
        </el-col>
      </el-form>
    </el-row>
</el-card>
    </div>
  </div>
</template>

<script>
// 引入获取学科列表api
import { simple as simple1 } from '../../api/hmmm/subjects.js'
// 引入获取目录列表api
import { simple as simple2 } from '../../api/hmmm/directorys.js'
// 引入公司列表api
import { list } from '../../api/hmmm/companys.js'
// 引入标签列表api
import { list as list2 } from '../../api/hmmm/tags.js'
// 引入城市列表
import { citys, provinces } from '../../api/hmmm/citys.js'
// 引入方向列表
import { direction, difficulty, questionType } from '../../api/hmmm/constants.js'
// 引入基础题库添加，修改,详情的api
import { add, update, detail } from '../../api/hmmm/questions.js'
// 引入富文本组件
import QuillEditor from '../components/quill-editor.vue'

// 配置腾讯云密钥
var COS = require('cos-js-sdk-v5')
// SECRETID 和 SECRETKEY请登录 https://console.cloud.tencent.com/cam/capi 进行查看和管理
var cos = new COS({
  SecretId: 'AKIDVuEQQClEW7iDYQ7d5Wp01oRyPfg4kPuE',
  SecretKey: 'IV1QeiYBbomX6SbZJ0Z1GKBrLbeT6Yt5'
})

export default {
  components: { QuillEditor },
  props: [],
  data () {
    return {
      type: this.$route.query.id,
      showOption: true,
      changeOption: true,
      input: '',
      radio: '',
      url: '',
      form: {
        subjectID: '',
        catalogID: '',
        enterpriseID: '',
        province: '',
        city: '',
        direction: '',
        questionType: '1',
        difficulty: '1',
        question: '',
        options: [{
          code: 'A',
          title: '',
          img: '',
          isRight: false
        }, {
          code: 'B',
          title: '',
          img: '',
          isRight: false
        }, {
          code: 'C',
          title: '',
          img: '',
          isRight: false
        }, {
          code: 'D',
          title: '',
          img: '',
          isRight: false
        }],
        videoURL: '',
        answer: '',
        remarks: '',
        tags: []
      },
      rules: {
        subjectID: [{
          required: true,
          message: '请选择学科',
          trigger: 'change'
        }],
        catalogID: [{
          required: true,
          message: '请选择目录',
          trigger: 'change'
        }],
        enterpriseID: [{
          required: true,
          message: '请选择公司',
          trigger: 'change'
        }],
        province: [{
          required: true,
          message: '请选择城市',
          trigger: 'change'
        }],
        city: [{
          required: true,
          message: '请选择',
          trigger: 'change'
        }],
        direction: [{
          required: true,
          message: '请选择方向',
          trigger: 'change'
        }],
        questionType: [{
          required: true,
          message: '题型不能为空',
          trigger: 'change'
        }],
        difficulty: [{
          required: true,
          message: '难度不能为空',
          trigger: 'change'
        }],
        question: [{
          required: true,
          message: '请输入题干',
          trigger: 'blur'
        }],
        option: [],
        videoURL: [],
        answer: [{
          required: true,
          message: '请输入答案解析',
          trigger: 'blur'
        }]
      },
      subjectNameOptions: [],
      directoryNameOptions: [],
      shortNameOptions: [],
      provinceOptions: [],
      cityOptions: [],
      directionOptions: [],
      questionTypeOptions: questionType,
      difficultyOptions: difficulty,
      tagsOptions: []
    }
  },
  computed: {},
  watch: {
  },
  created () {
    // 初始化获取列表
    this.getInitial()
    // 初始化判断是试题修改还是添加，如果是修改则发送请求获取数据，表单回显
  },
  mounted () {},
  methods: {
    // 提交表单
    onSubmit () {
      // 将数组转换为字符串
      this.form.tags = this.form.tags.toString()
      this.$refs.formRef.validate(async valid => {
        if (!valid) return
        // TODO 提交表单
        // 通过type区分为添加还是修改
        // 有id则为修改，否则为添加
        if (this.type) {
          await update({
            ...this.form, id: Number(this.type)
          })
          this.$message.success('修改成功')
          return this.$router.push('list')
        }
        await add(this.form)
        this.$message.success('添加成功')
        this.$router.push('list')
      })
    },
    async getInitial () {
      // 初始化判断是试题修改还是添加
      if (this.type) {
        // 修改则请求试题的数据
        const { data } = await detail({
          id: Number(this.type)
        })
        // 表单回显
        this.form = data
        // 试题回显
        this.form.tags = data.tags.split(',')
        // 目录列表回显
        const res = await simple2({
          subjectID: this.form.subjectID
        })
        // 试题标签列表回显
        const { data: { items } } = await list2({
          subjectID: this.form.subjectID
        })
        this.directoryNameOptions = res.data
        this.tagsOptions = items

        // 选项回显
        this.form.options = this.form.options.map(t => {
          t.isRight = t.isRight === 1
          return t
        })
        // 题干回显
        this.$refs.questionRef.content = this.form.question
        // 答案解析回显
        this.$refs.answerRef.content = this.form.answer
        // 选项回显类型判断
        this.changeOption = this.form.questionType === '1'
        this.showOption = this.form.questionType !== '3'
        // 选项回显选中
        if (this.changeOption) {
          const index = this.form.options.findIndex(t => t.isRight === true)
          if (index !== -1) {
            this.radio = index
          } else {
            this.radio = ''
          }
        }
      }
      // 解构获取学科列表数据
      const { data } = await simple1()
      // 获取公司列表数据
      const { data: { items } } = await list()
      // 获取城市列表
      const res = provinces()
      this.provinceOptions = res
      // 赋值给选项框
      this.shortNameOptions = items
      this.subjectNameOptions = data
      this.directionOptions = direction
    },
    async chooseSub () {
      // 当学科选择器值发生改变时判断如果有值，则重置目录下拉框的列表数据
      if (this.form.subjectID) {
        // 如果有值，请求目录下拉框数据,传入学科id(即value值)
        const { data } = await simple2({
          subjectID: this.form.subjectID
        })
        // 清空目录的值
        this.form.catalogID = ''
        // 如果有值，请求标签下拉框数据,传入学科id(即value值)
        const { data: { items } } = await list2({
          subjectID: this.form.subjectID
        })
        // 清空试题的值
        this.form.tags = []
        // 将试题标签赋值
        this.tagsOptions = items
        // 将目录列表赋值
        this.directoryNameOptions = data
      } else {
        this.directoryNameOptions = []
      }
    },
    // 省份获取值进行城市选择
    chooseCity () {
      // 如果province有值，发送citys请求，传入省份名称
      if (this.form.province) {
        const res = citys(this.form.province)
        this.cityOptions = res
      } else {
        // 否则就是没有数据
        this.cityOptions = []
      }
    },
    // 下拉框下拉时禁止页面滚动

    changeItem (val) {
      // 在每次变化题型时让单选框和复选框的内容重置
      if (val === '1') {
        // 单选框显示，复选框隐藏
        this.changeOption = true
        // 题型不为3显示选项框
        this.showOption = true
        // 重置 单选框选项选择
        this.radio = ''
      } else if (val === '2') {
        // 单选框显示，复选框隐藏
        this.changeOption = false
        // 题型不为3显示选项框
        this.showOption = true
        // 重置 选项选择
        // 排他法，让所有项全为false
        this.form.options.forEach(t => {
          t.isRight = false
        })
      } else {
        // 题型为3隐藏选项框
        this.showOption = false
        this.form.options = []
      }
    },
    AddOption () {
    // 点击新增选项按钮在选项列表中添加对象
      this.form.options.push({
        code: String.fromCharCode('A'.charCodeAt(0) + this.form.options.length),
        title: '',
        img: '',
        isRight: false
      })
    },
    delOption (i, event) {
      // 阻止冒泡行为
      event.stopPropagation()
      // 删除目标选项
      this.optionOptions.splice(i, 1)
      // 实现删除中间选项，下方选项自动补齐
      // 使用map每次删除成功后重新排列一次选项的label
      const obj = this.optionOptions.map((item, index) => {
        item.code = String.fromCharCode('A'.charCodeAt(0) + index)
        return item
      })
      this.optionOptions = obj
    },
    /* 图片 */
    // 上传之前
    // 上传图片
    onUpload (options, index) {
      // 得到文件对象，来上传
      const file = options.file
      // 显示进度条
      let url
      cos.putObject({
        Bucket: 'rzzt-1258843348', /* 必须 */
        Region: 'ap-chengdu', /* 存储桶所在地域，必须字段 */
        Key: Date.now() + file.name, /* 必须 */
        StorageClass: 'STANDARD',
        Body: file // 上传文件对象
      }, (err, data) => {
        // 上传中状态关闭
        console.log(err || data)
        // 把图片放到fileList当中
        // 上面已经push进fileList中了，这里只需要直接修改图片
        url = 'http://' + data.Location
        this.form.options[index].img = url
        // 关闭进度条
        this.showPercent = false
      })
    },
    // 实现单选框点击哪个，哪个就是正确选项，即isRight为true
    optionChange (val) {
      // 排他法，先让所有项全为false
      this.form.options.forEach(t => {
        t.isRight = false
      })
      // 目标索引号处为true
      this.form.options[val].isRight = true
    },
    // 获取题干内容
    getQuestion (val) {
      this.form.question = val
    },
    // 获取解析内容
    getAnswer (val) {
      this.form.answer = val
    },
    tagChange () {
      console.log(this.from.tags)
    }
  }
}
</script>

<style scoped lang='scss'>
.clearfix:before,
  .clearfix:after {
    display: table;
    content: "";
  }
  .clearfix:after {
    clear: both
  }
 ::v-deep(.el-checkbox__label) {
    margin-left: 3.5px !important;
    margin-top: 1px !important;
  }
  .option {
    display: flex;
    height: 300px;
    flex-direction: column;
    justify-content: space-evenly;
    .option-radio {
      margin: 0;
    }
  }
  .avatar-uploader {
    width: 50px;
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
    cursor: pointer;
    margin: 0;
    margin-left: 4px;
    // position: relative;
    // overflow: hidden;
  }
  .cityRay {
    display: flex;
      .city {
        flex-shrink: 0;
      }
  }

 .option_item {
    height: 80px;
    padding-bottom: 20px;
    .el-radio {
      margin: 0;
      width: 50.46px;
     .el-radio__label{
        width: 36.46px !important;
      }
    }
  }
.el-checkbox {
  width: 50.46px;
}
  .avatar-uploader {
    position: relative;
    display: inline-block;
    width: 100px;
    height: 60px;
    text-align: center;
    line-height: 60px;
    .el-upload {
    display: inline-block;
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
    cursor: pointer;
  }
    .el-upload:hover {
    border-color: #409EFF;
  }
  }

  .icon {
    position: absolute;
    top: -9px;
    right: -9px;
    height: 18px;
    width: 18px;
    border-radius: 50%;
    font-size: 18px;
    background-color: #fff;
    color: #8c939d;
  }
  /* .avatar {
    width: 178px;
    height: 178px;
    display: inline-block;
  } */
</style>
